/*
 * Created on 2007-2-18
 *
 * TODO 
 */
package jacky.lanlan.song.extension.struts.action;

import static org.mockito.Mockito.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.junit.Test;
import org.mockito.MockitoAnnotations.Mock;

import jacky.lanlan.song.extension.struts.mock.DelegatingValueStack;
import jacky.lanlan.song.resource.ResourceUtils;

/**
 * @author Jacky.Song
 *
 * 完整的下载过程测试。
 */
public class DownloadTest_FullStack extends BaseStrutsActionTest {

	@Mock private HttpServletResponse response;
	private DelegatingValueStack mockVS;
	private static final int FILE_SIZE=1024*10;//10k
	private static byte[] log4jFileContent;
	private byte[] actualContent;
	private int counter;

	static {
		try {
			//得到log4j.properties的内容作为参考
			File log4j=ResourceUtils.getFile("classpath:log4j.properties");
			FileChannel fc=new FileInputStream(log4j).getChannel();
			ByteBuffer bb=ByteBuffer.allocate(FILE_SIZE);
			fc.read(bb);
			bb.flip();
			log4jFileContent=new byte[bb.limit()];
			bb.get(log4jFileContent);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public void onSetUp() {
		actualContent=new byte[log4jFileContent.length];
		
		mockVS=new DelegatingValueStack();
		mockVS.setMockResponse(response);

		ServletOutputStream mockOS=new ServletOutputStream () {
			@Override
			public void write(int b) throws IOException {
				actualContent[counter]=(byte) b;
				counter++;
			}
		};
		
		try {
			stub(response.getOutputStream()).toReturn(mockOS);
		}
		catch (IOException e) {
			throw new RuntimeException(e);
		}
		
	}

	@Test
	public void testDownload() throws Exception {
		setResponseWrapper(new HttpServletResponseWrapper(response));
		setRequestPathInfo("/POJOTest!download");

		actionPerform();

		verify(response).setContentType("application/properties");

		verify(response).setHeader("Content-Disposition", "attachment;" + " filename="
				+ new String("log4j.properties".getBytes(), "ISO-8859-1"));

    verifyNoActionErrors();
		
    assertArrayEquals("应该得到log4j.properties文件的字节流",log4jFileContent, actualContent);
	}

	public void onTearDown() {
		actualContent=null;
		response=null;
	}

}
